package com.datastructure.test.spiralmatrix;

import java.util.ArrayDeque;
import java.util.Deque;

public class SpiralMatrix {

    public static void main(String[] args) {
        SpiralMatrix spiralMatrix = new SpiralMatrix();
        int[][] matrix = spiralMatrix.Matrix(3);
        System.out.println(matrix);
    }

    public int[][] Matrix (int n) {
        // write code here
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 1; i <= n*n; i++) {
            deque.add(i);
        }
        int[][] matrix = new int[n][n];
        int top = 0, bottom = matrix.length-1;
        int left = 0, right = matrix[0].length-1;
        while( top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2 ){
            //上面  左到右
            for(int i = left; i <= right; i++){
                matrix[top][i]=deque.poll();
            }

            //右边 上到下
            for(int i = top+1; i <= bottom; i++){
                matrix[i][right]=deque.poll();
            }

            //下面  右到左
            for(int i = right-1; top!=bottom && i>=left; i--){
                matrix[bottom][i]=deque.poll();
            }

            //左边 下到上
            for(int i = bottom-1; left!=right && i>=top+1; i--){
                matrix[i][left]=deque.poll();
            }
            // 遍历完一圈之后，所有往里面靠
            ++top;
            --bottom;
            ++left;
            --right;
        }
        return matrix;
    }
}
